package com.aruba.ffmpegsyncapplication;

import android.content.Context;
import android.graphics.PixelFormat;
import android.util.AttributeSet;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

/**
 * Created by aruba on 2020/6/30.
 */
public class FFmpegPlayView extends SurfaceView implements SurfaceHolder.Callback {
    static {
        System.loadLibrary("native-lib");
    }

    public FFmpegPlayView(Context context) {
        this(context, null);
    }

    public FFmpegPlayView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public FFmpegPlayView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        setKeepScreenOn(true);
        //设置一个像素占4字节
        getHolder().setFormat(PixelFormat.RGBA_8888);

        getHolder().addCallback(this);
    }

    /**
     * 开始播放
     */
    public synchronized void play(String path) {
        stop();

        //调用natvie方法开始解码
        render(path);
    }

    public synchronized void stop() {
        if (isPlaying()) {
            //调用natvie方法停止播放
            stopPlay();
        }
    }

    public native boolean isPlaying();

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        stop();
    }

    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {

    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
        display(surfaceHolder.getSurface());
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {

    }

    /**
     * 设置surface，用于native层原生绘制
     *
     * @param surface
     */
    public native void display(Surface surface);

    /**
     * 开始播放
     *
     * @param filePath
     * @return
     */
    public native int render(String filePath);

    public native void stopPlay();
}
